<template>
  <div class="app-container">
    <!--基本信息-->
    <div>
      <el-card class="box-cardfd">
        <div slot="header" class="clearfix">
          <span>基本信息</span>
        </div>
        <el-form :model="form" label-width="130px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="申请单号" required>
                <el-input v-model="form.code" placeholder="系统自动生成" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请主题" required>
                <el-input v-model="form.topic" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="申请日期" required>
                <el-date-picker v-model="form.date" placeholder="请选择日期" style="width: 465px"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请人">
                <el-input v-model="form.applicant" placeholder="艾如波" disabled></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="申请部门">
                <el-input v-model="form.department" placeholder="采购部" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式">
                <el-input v-model="form.contact" placeholder="18340411600" disabled></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="申请事由" required>
                <el-input type="textarea" v-model="form.affair" placeholder="请输入申请事由" cols="8" rows="4"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="备注">
                <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" cols="8" rows="4"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
    <!--选择设备-->
    <div>
      <div>
        <el-card class="box-card2f">
          <div slot="header" class="clearfix">
            <span>设备明细</span>
          </div>
          <div>
            <el-button @click="addEquipment">添加</el-button>
            <el-button @click="addNewEquipment">新建新设备</el-button>
            <el-button @click="removeSelected">移除</el-button>
          </div>
          <el-table :data="tableData" ref="registTable" style="width: 100%" stripe>
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column label="序号" prop="id" width="80" align="center" fixed></el-table-column>
            <el-table-column label="操作" width="100" fixed="left" align="center">
              <template slot-scope="scope">
                <el-button size="mini" @click="moveEquipment(scope.row)">移除</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="code" label="设备编号" width="170" align="center"></el-table-column>
            <el-table-column prop="name" label="设备名称" align="center"></el-table-column>
            <el-table-column prop="specification" label="规格型号" align="center"></el-table-column>
            <el-table-column prop="type" label="设备类型" align="center"></el-table-column>
            <el-table-column prop="brand" label="品牌" align="center"></el-table-column>
            <el-table-column prop="unit" label="单位" align="center"></el-table-column>
            <el-table-column prop="openingInventory" label="当前库存" align="center"></el-table-column>
            <el-table-column label="参考价格" prop="reference" width="180" align="center">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.reference" :min="0" precision="2"
                  style="width: 150px"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="购买数量" prop="quantity" width="180" align="center">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.quantity" :min="1" :max="scope.row.openingInventory"
                  style="width: 150px"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="金额" prop="estimate">
              <template slot-scope="scope">
                {{ (scope.row.reference * scope.row.quantity).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark" align="center" width="180">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remark" placeholder="请输入备注"></el-input>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 25px; margin-left: 1005px">
            <span>总数量：{{ totalQuantity }}</span>
            <span style="margin-left: 20px">总金额：{{ totalAmount.toFixed(2) }}</span>
          </div>
        </el-card>
      </div>
      <!--子设备选择框-->
      <el-dialog title="选择设备" :visible.sync="dialogVisible" width="60%">
        <div>
          <el-input placeholder="请输入设备编号/名称/规格型号" v-model="searchInput"
            style="width: 20%; margin-right: 10px"></el-input>
          <el-select placeholder="请选择设备类型" v-model="selectedType" style="width: 20%; margin-right: 10px">
            <el-option label="生产设备" value="生产设备"></el-option>
          </el-select>
          <el-select placeholder="请选择使用部门" v-model="selectedDepartment" style="width: 20%; margin-right: 10px">
            <el-option label="生产部门" value="生产部门"></el-option>
          </el-select>
          <el-button type="primary" @click="handleSearch2">查询</el-button>
          <el-button @click="handleReset2">重置</el-button>
        </div>

        <el-table size="mini" :cell-style="{ padding: '0px' }" :row-style="{ height: '35px' }" :data="filteredData"
          style="width: 100%; margin-top: 20px" stripe ref="registTable2" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="eid" label="序号" width="50" align="center">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="code" label="设备编号" width="170" align="center"></el-table-column>
          <el-table-column prop="name" label="设备名称" align="center"></el-table-column>
          <el-table-column prop="specification" label="规格型号" align="center"></el-table-column>
          <el-table-column prop="type" label="设备类型" align="center"></el-table-column>
          <el-table-column prop="brand" label="品牌" align="center"></el-table-column>
          <el-table-column prop="unit" label="单位" align="center"></el-table-column>
          <el-table-column prop="list[0].openingInventory" label="当前库存" align="center"></el-table-column>
        </el-table>

        <el-pagination background layout="prev, pager, next, sizes, total" :total="total" :page-size.sync="pageSize"
          :current-page.sync="currentPage" @size-change="handlePageChange2" @current-change="handlePageChange2"
          style="margin-top: 20px" />

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确认</el-button>
        </div>
      </el-dialog>
    </div>

    <!--关联文件-->
    <div>
      <el-card class="box-card4f">
        <div slot="header" class="clearfix">
          <span>关联文件</span>
        </div>
        <el-button-group style="margin-bottom: 20px">
          <el-upload ref="upload2" action="http://localhost:9289/maintenance/upload2" :on-success="handleUploadSuccess2"
            :file-list="fileList" :auto-upload="true" :show-file-list="false" :before-upload="beforeUpload">
            <el-button type="primary">上传文档</el-button>
          </el-upload>
          <el-button @click="removeSelectedRows2">移除</el-button>
        </el-button-group>
        <el-table :data="documents" style="width: 100%" border @selection-change="handleSelectionChange37">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="name" label="文件名"></el-table-column>
          <el-table-column prop="uploadDate" label="上传时间"></el-table-column>
          <el-table-column prop="uploader" label="上传者"></el-table-column>
          <el-table-column prop="size" label="文档大小"></el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button type="text" @click="removeRow3(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <el-footer class="footer">
      <el-button @click="handleCancel" style="margin-top: 20px; margin-left: -140px">关闭</el-button>
      <el-button type="primary" @click="handleConfirm2" style="margin-top: 20px; margin-left: 20px">确认</el-button>
    </el-footer>
    <div style="height: 150px"></div>
  </div>
</template>

<script>
import { listEquipment2, listEquipment } from "@/api/eastjet-maintenance/sb/sb";
import { Insertkan, InsertApplicationBei } from "@/api/eastjet-maintenance/caig/cai";
import { SelectLedger2 } from "@/api/eastjet-maintenance/tai/tai";
export default {
  data() {
    return {
      searchInput: "",
      selectedType: "",
      selectedDepartment: "",
      filteredData: [], //设备数据
      filteredData2: [], //选择存放数据
      currentPage: 1,
      pageSize: 10,
      total: 20,
      dialogVisible: false,
      tableData: [],
      tableData2: [],
      form: {
        code: "",
        topic: "",
        date: "",
        applicant: this.$store.state.user.name,
        department: "采购部",
        contact: "584986658",
        affair: "",
        state: 1,
        remark: "",
        quantity: "",
        amount: "",
        tableData: [],
        documents: [],
        usname: "",
        is_delete: 0,
      },
      //关联文件上传
      documents: [],
      fileList: [],
      multipleSelection: [],
    };
  },
  computed: {
    totalQuantity() {
      return this.tableData.reduce(
        (sum, item) => sum + (item.quantity || 0),
        0
      );
    },
    totalAmount() {
      return this.tableData.reduce(
        (sum, item) => sum + item.reference * item.quantity,
        0
      );
    },
  },
  created() {
    this.getList();
  },
  methods: {
    handleSelectionChange(val) {
      this.filteredData2 = val;
    },
    //选择设备分页事件
    handlePageChange2(size) {
      listEquipment2(this.currentPage, this.pageSize).then((res) => {
        this.filteredData = res.data.data.list;
      });
    },
    getList() {
      SelectLedger2(this.currentPage, this.pageSize).then((res) => {
        this.filteredData = res.data.data.list;
        this.filteredData.forEach(item => {
          for (let i = 1; i < item.list.length; i++) {
            item.list[0].openingTotals += item.list[i].openingTotals
            item.list[0].openingInventory += item.list[i].openingInventory
          }
        })
        this.total = res.data.data.total;
      });
    },
    //上传文件大小判断
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isLt10M) {
        this.$message.error("上传文件大小不能超过 10MB!");
      }
      return isLt10M;
    },
    //关联文件上传
    removeRow2(index) {
      this.childDevices.splice(index, 1);
    },
    //删除文件
    removeSelectedRows2() {
      this.childDevices = this.childDevices.filter(
        (item) => !this.multipleSelection.includes(item)
      );
    },
    //文件上传成功时候
    handleUploadSuccess2(response, file, fileList) {
      this.documents.push({
        name: file.name,
        url: file.url,
        uploadDate: new Date().toLocaleDateString('zh').replaceAll('/', '-'),
        uploader: this.$store.state.user.name,
        size: file.size + " KB",
      });
      console.log("数据2", this.documents);
    },
    //增加设备确认
    handleConfirm() {
      // 处理确认操作
      if (this.tableData.length == 0) {
        for (let i = 0; i < this.filteredData2.length; i++) {
          this.tableData.push({
            id: this.tableData.length + 1,
            code: this.filteredData2[i].code,
            name: this.filteredData2[i].name,
            specification: this.filteredData2[i].specification,
            type: this.filteredData2[i].type,
            brand: this.filteredData2[i].brand,
            unit: this.filteredData2[i].unit,
            openingInventory: this.filteredData2[i].list[0].openingInventory,
            reference: 1,
            quantity: 1,
            tombstone: 0,
            estimate: 2,
            requestNumber: "",
          });
        }
      } else {
        for (let i = 0; i < this.tableData.length; i++) {
          for (let j = 0; j < this.filteredData2.length; j++) {
            if (this.tableData[i].code == this.filteredData2[j].code) {
              this.tableData[i].quantity += 1;
              this.filteredData2.splice(j, 1);
            }
          }
        }

        for (let i = 0; i < this.filteredData2.length; i++) {
          this.tableData.push({
            id: this.tableData.length + 1,
            code: this.filteredData2[i].code,
            name: this.filteredData2[i].name,
            specification: this.filteredData2[i].specification,
            type: this.filteredData2[i].type,
            brand: this.filteredData2[i].brand,
            unit: this.filteredData2[i].unit,
            openingInventory: this.filteredData2[i].list[0].openingInventory,
            reference: 1,
            quantity: 1,
            tombstone: 0,
            estimate: 2,
            requestNumber: "",
          });
        }
      }
      this.$refs.registTable2.clearSelection();
      this.dialogVisible = false;
    },
    //采购明细添加
    // mingxi() {
    //   for (let i = 0; i < this.tableData.length; i++) {
    //     this.tableData[i].estimate =
    //       this.tableData[i].reference * this.tableData[i].quantity;
    //   }
    //   InsertSbdeice(this.tableData).then((res) => {
    //     if (res.data.code == 520) {
    //       this.$refs.upload2.submit();
    //       this.$router.go(-1);
    //     } else {
    //       this.$notify.error({
    //         title: "失败",
    //         message: "这是一条失败的提示消息",
    //       });
    //     }
    //   });
    // },
    cgong(res, file) {
      this.dialogVisible = false;
    },
    handleConfirm2() {
      this.form.quantity = this.totalQuantity;
      this.form.amount = this.totalAmount;
      this.form.tableData = this.tableData;
      this.form.usname = this.$store.state.user.name;
      this.form.documents = this.documents;
      InsertApplicationBei(this.form).then((res) => {
        if (res.data.code == 520) {
          this.$router.go(-1);
        } else {
          this.$notify.error({
            title: "失败",
            message: "这是一条失败的提示消息",
          });
        }
      });
    },
    //确认取消
    handleCancel() {
      // alert("上传");
      // this.$refs.upload2.submit();
      this.$router.go(-1);
    },
    addEquipment() {
      // 新增设备的逻辑
      this.dialogVisible = true;
    },
    addNewEquipment() {
      // 新建新设备的逻辑
    },
    moveEquipment(row) {
      // 移除Equipment的逻辑
      const index = this.tableData.indexOf(row);
      if (index > -1) {
        this.tableData.splice(index, 1);
      }
    },
    removeSelected() {
      // 根据选中项移除设备的逻辑
      const selected = this.$refs.registTable.selection;
      console.log("数据", selected);
      this.tableData = this.tableData.filter(
        (item) => !selected.includes(item)
      );
    },
  },
};
</script>

<style scoped>
.fixed-footer-page {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.footer {
  text-align: center;
  background-color: #eeeded;
  position: fixed;
  bottom: 0;
  z-index: 12;
  width: 100%;
}

.app-container {
  width: 1300px;
  /* height: 1000px; */
}

.box-cardfd {
  width: 1254px;
  margin-left: 10px;
  margin-top: 10px;
  height: 480px;
}

.box-card2f {
  width: 1254px;
  margin-left: 10px;
  margin-top: 10px;
}

.box-card4f {
  width: 1254px;
  margin-left: 10px;
  margin-top: 10px;
}
</style>
